package com.yich.dingserver;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import com.sun.mail.util.MailSSLSocketFactory;
import com.yich.webcliemt.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.DataOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class DingService extends AccessibilityService {

    private static String TAG = "DingService";

    public static DingService instance;

    /**
     * 大开钉钉的大步骤
     */
    public final static int STEP_OPEN_HOME = 1;
    public final static int STEP_OPEN_KAOQIN = 2;
    public final static int STEP_DO_KAOQIN = 3;
    public final static int STEP_NET_NOT_STADEABLE = 4;//打卡网络环境不好稍后上传结果
    public final static int STEP_KAOQIN_SUCC = 5;//打卡成功 检测当前弹窗
    private int index = STEP_OPEN_HOME;//
    //打卡指令
    public final static int COMMAND_KAOQIN_AM = 1;//早上打卡
    public final static int COMMAND_KAOQIN_PM = 2;//下午打卡
    public final static int COMMAND_UPDATE_KAOQIN_PM = 3;//更新下午打卡
    public final static int COMMAND_NONE = 4;//默认指令
    private int mCommand = COMMAND_NONE;
    //打卡指令对应对的扣扣消息
    private final static String QQ_TEXT_AM = " 上班打卡";
    private final static String QQ_TEXT_PM = " 下班打卡";
    private static final String QQ_TEXT_STOP_DINGDING = " 关闭钉钉";
    private static final String QQ_TEXT_UPDATE_KAOQIN = " 更新下班打卡";
    private static final String MAIL_TEXT = "到达打卡界面";

    //各个打卡指令的小步骤
    private int mMiniStep = 0;

    //    private final static String PKG_DINGDING = "com.alibaba.android.rimet";
    private final static String PKG_DINGDING = "com.seeyon.cmp";
    //    private final static String PKG_QQ = "com.tencent.mobileqq";
    public final static int MAX_CLICK_TIMES = 3;//最多尝试点击的次数
    private boolean canKaoqinPageClickable = false;
    private int kaoQinChangeCount = 0;
    private int tryCounts = 0;
    //打卡时候有发送邮件
    private boolean hasSendMail = false;
    private Rect webRect;
    private KeyguardManager.KeyguardLock kl;
    private static Context mContext;
    public final static int LIGHT_START = 4;
    public final static int CLICK_POWER_BTN = 1;
    public final static int LIGHT_END = 2;
    public final static int LIGHT_CHECK = 3;
    public final static int SEND_MESG = 5;
    public final static int DAKA = 6;
    public final static int DAKAKAOQIN = 7;
    public final static int QIANDAO = 8;
    public static int mCountBtnCLick = 0;//电源键模拟的次数
    public final static int DELAY_TIME = 500;

    private boolean isMoveUp = false;
    private boolean isClickKaoqin = false;
    private boolean isDakFinish = false;

    KeyguardManager km;
    @SuppressLint("HandlerLeak")
    public Handler lightHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == CLICK_POWER_BTN || msg.what == LIGHT_START) {
                mCountBtnCLick++;
                Log.w(TAG, "light screen by power btn,try time:" + mCountBtnCLick);
                execShellCmd("input keyevent " + KeyEvent.KEYCODE_POWER);
                sendEmptyMessageDelayed(LIGHT_CHECK, DELAY_TIME);
            }
            if (msg.what == LIGHT_CHECK) {
                if (mContext != null) {
                    PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
                    if (pm.isScreenOn()) {
                        sendEmptyMessage(LIGHT_END);
                    } else {
                        sendEmptyMessageDelayed(CLICK_POWER_BTN, DELAY_TIME);
                    }
                } else {
                    Log.e(TAG, "DingService is dead ,please reset");
                }
            }
            if (msg.what == LIGHT_END) {
                mCountBtnCLick = 0;
            }
            if (msg.what == SEND_MESG) {
                keepScreem();
            }
            if (msg.what == DAKA) {
                clickViewByXy(x, y);
            }
            if (msg.what == DAKAKAOQIN) {
                clickViewByXy(x, y);
            }
            if (msg.what == QIANDAO) {
                doQianDao();
            }
        }
    };

    @Override
    public void onCreate() {
        Log.e(TAG, "----######---server is onCreate ----######---");
        super.onCreate();
        // 解锁屏幕
        km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        kl = km.newKeyguardLock("unLock");
        // 设置前台应用
        createNotifition();
        EventBus.getDefault().register(this);
        mContext = this;
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        EventTest(event);
    }

    private void EventTest(AccessibilityEvent event) {
        //AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 标题发生变化
        //CONTENT_CHANGE_TYPE_UNDEFINED 标题发生变化
        //AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED
        Log.i(TAG, "EventTest:    "
                + " [action] " + event.getAction()
                + " [event]  " + event.getEventType()
                + " [types]  " + event.getContentChangeTypes()
                + " [desc]   " + event.getContentDescription()
                + " [pak]    " + event.getPackageName()
                + " [text]   " + event.getText().toString()
        );

        if (event.getText().toString().contains("长颈怒")) {
            prepareForKaoQin();
            event.recycle();
            return;
        }

        if (event.getPackageName().toString().equals("com.android.settings")) {
            log("           寻找钉钉App设置 点击 ===");
            Log.e(TAG, "EventTest:    " + event.getText().toString());

            if (stepIndex != 0) {
                return;
            }

            final AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
            List<AccessibilityNodeInfo> right = null;
            try {
                right = nodeInfo.findAccessibilityNodeInfosByViewId("com.android.settings:id/right_button");
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (right != null) {
                    Log.e(TAG, "EventTest:   right " + right.size());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                comClickByID("com.android.settings:id/right_button");
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                comClickByID("android:id/button1");
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }

           /* new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    List<AccessibilityNodeInfo> commmite = nodeInfo.findAccessibilityNodeInfosByViewId("android:id/button1");
                    Log.e(TAG, "EventTest:   commmite " + commmite.size());
                    log("           3、寻找钉钉App设置 点击确定");
                    comClickByID("android:id/button1");
                }
            }, 3000);*/
            return;
        }

        if (stepIndex != 3) {
            getViewAndClick(getRootInActiveWindow());
        }
    }

    int x = 0;
    int y = 0;

    private String strFlag = "考勤打卡";

    //点击 文字
    private void getViewAndClick(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }

        CharSequence contentDescription = nodeInfo.getContentDescription();
        if (contentDescription != null && !contentDescription.toString().isEmpty()) {

            Rect rect = new Rect();
            nodeInfo.getBoundsInScreen(rect);
            //Log.d(TAG, "[getViewAndClick]: " + rect.left + " " + rect.top + " " + rect.right + " " + rect.bottom + "  " + str);
            x = (rect.left + rect.right) / 2;
            y = (rect.top + rect.bottom) / 2;
            String cmd = "input tap " + String.valueOf(x) + " " + String.valueOf(y);

            Log.i(TAG,
                    "[contentDescription]:   " + contentDescription
                            + "   nodeInfo.size:   " + nodeInfo.getChildCount()
                            + "   getViewIdResourceName:   " + nodeInfo.getViewIdResourceName()
                            + "   getChildCount:   " + nodeInfo.getParent().getChildCount()
            );

            if (contentDescription.toString().contains("北京市昌平区回龙观")) {
                //打卡成功
                doQianDao();
                Log.e(TAG, "打卡成功了:" + contentDescription.toString());
                //lightHandler.removeMessages(SEND_MESG);
                //lightHandler.sendEmptyMessageDelayed(SEND_MESG, 10000);
                stepIndex = 3;
                return;
            }

            if (contentDescription.toString().equals("审批") && stepIndex != 3) {
                strFlag = "打卡";
                return;
            }

            if (contentDescription.toString().equals(strFlag) && stepIndex != 3) {

                Log.w(TAG, "[getViewAndClick]:   contentDescription执行点击 cmd" + cmd + " [strFlag] " + strFlag + "     nodeInfo.getChildCount() = " + nodeInfo.getChildCount());

                if (contentDescription.toString().equals("打卡") && nodeInfo.getChildCount() != 0) {
                    Log.w(TAG, "[getViewAndClick]:   contentDescription执行点击 正在的打卡" + cmd + " [strFlag] " + strFlag + "     nodeInfo.getChildCount() = " + nodeInfo.getChildCount());
                    doQianDao();
                } else if (contentDescription.toString().equals("打卡") && nodeInfo.getChildCount() == 0) {
//                    lightHandler.removeMessages(DAKA);
//                    lightHandler.sendEmptyMessageDelayed(DAKA, 200);

                    if (x < 200 || y < 1100) {

                    } else {
                        clickViewByXy(x, y);
                    }
                } else {
                    clickViewByXy(x, y);
//                    lightHandler.removeMessages(DAKAKAOQIN);
//                    lightHandler.sendEmptyMessageDelayed(DAKAKAOQIN, 200);
                }
                return;
                /*Log.d(TAG, "[getViewAndClick]:   执行点击 --- isClickable " + nodeInfo.isClickable());
                boolean b = nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                nodeInfo.getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
                Log.d(TAG, "[getViewAndClick]:   执行点击 " + b);*/
            }
        }

        if (nodeInfo.getChildCount() == 0) {
            return;
        }
        for (int i = 0; i < nodeInfo.getChildCount(); i++) {
            AccessibilityNodeInfo child = nodeInfo.getChild(i);
            getViewAndClick(child);
        }
    }


    private void initCommand(int commandKaoqinPm) {
        mMiniStep = 0;
        mCommand = commandKaoqinPm;
        index = STEP_OPEN_HOME;
        canKaoqinPageClickable = false;
        kaoQinChangeCount = 0;
        tryCounts = 0;//单次命令尝试点击次数
        hasSendMail = false;
    }

    public void startAPP(final String appPackageName) {
        try {
            new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    log("           打开App设置");
                    Intent mIntent = new Intent();
                    mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    mIntent.setData(Uri.fromParts("package", appPackageName, null));
                    startActivity(mIntent);

                    //android:id/button1 确定
                    //com.android.settings

                    //com.android.settings:id/right_button
                    //强行停止
                }
            }, 2000);
            new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    log("           3、启动钉钉App设置");
                    Intent intent = getPackageManager().getLaunchIntentForPackage(appPackageName);
                    startActivity(intent);
                }
            }, 8000);

        } catch (Exception e) {
            e.printStackTrace();
            toast("没有安装：" + e.toString());

        }
    }

    private int stepIndex = -1;

    /**
     * 1、亮屏
     * 2、打开桌面
     * 3、启动App流程
     */
    private void prepareForKaoQin() {
        stepIndex = 0;
        strFlag = "考勤打卡";
        try {
            log("           亮屏幕");
            wakeUpAndUnlock(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //clickMenue();
        //keepScreem();
        /*if (checkTime() == 0) {
            toast("未到打卡时间");
            return;
        }*/

        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                log("           打开桌面");
                performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
                startAPP(PKG_DINGDING);
            }
        }, 1000);
    }

    private void log(String str) {
        Log.w(TAG, str);
    }

    private int checkTime() {

        Calendar cal = Calendar.getInstance();// 当前日期
        int hour = cal.get(Calendar.HOUR_OF_DAY);// 获取小时
        int minute = cal.get(Calendar.MINUTE);// 获取分钟
        int minuteOfDay = hour * 60 + minute;// 从0:00分开是到目前为止的分钟数

        final int start1 = 20;// 起始时间 00:20的分钟数
        final int end1 = 8 * 60 + 30;// 结束时间 8:30的分钟数

        final int start2 = 8 * 60 + 30;
        final int end2 = 9 * 60;

        final int start3 = 9 * 60;
        final int end3 = 9 * 60 + 30;

        final int start4 = 17 * 60 + 30;
        final int end4 = 18 * 60;

        final int start5 = 18 * 60;
        final int end5 = 18 * 60 + 30;

        final int start6 = 18 * 60 + 30;
        if (minuteOfDay >= start1 && minuteOfDay <= end1) {
            SPUtils.put(getApplicationContext(), "NUM", 1);
            return 1;
        }
        if (minuteOfDay >= start2 && minuteOfDay <= end2) {
            SPUtils.put(getApplicationContext(), "NUM", 2);
            return 2;
        }
        if (minuteOfDay >= start3 && minuteOfDay <= end3) {
            SPUtils.put(getApplicationContext(), "NUM", 3);
            return 3;
        }
        if (minuteOfDay >= start4) {
            return (int) SPUtils.get(getApplicationContext(), "NUM", 1);
        }
//        if (minuteOfDay >= start5 && minuteOfDay <= end5) {
//            return 2;
//        }
//        if (minuteOfDay >= start6) {
//            return 3;
//        }
        Log.e(TAG, "OpenQianDao(DingService.java:445)" + "----还没到打卡时间 慌什么 ---");
        return 0;
    }

    private void doQianDao() {
        log("           真正的打卡点击  -------------------------------");

        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    GestureDescription.Builder localBuilder = new GestureDescription.Builder();
                    Path path = new Path();
                    path.moveTo(525, 1515);//140 1448  536 1231 525 1250
                    path.lineTo(525, 1517);//140 1449
                    localBuilder.addStroke(new GestureDescription.StrokeDescription(path, 150L, 100L));
                    dispatchGesture(localBuilder.build(), new GestureResultCallback() {
                        public void onCancelled(GestureDescription paramAnonymousGestureDescription) {
                            super.onCancelled(paramAnonymousGestureDescription);
                            Log.e(TAG, "------------------------- 打卡失败 ---------------------------------");
                        }

                        public void onCompleted(GestureDescription paramAnonymousGestureDescription) {
                            super.onCompleted(paramAnonymousGestureDescription);
                            isDakFinish = true;
                            index = STEP_KAOQIN_SUCC;

                            Log.e(TAG, "打卡成功了????");
                            lightHandler.removeMessages(SEND_MESG);
                            lightHandler.sendEmptyMessageDelayed(SEND_MESG, 5000);
                            stepIndex = 3;

                            Log.w(TAG, "------------------------- 打卡完成 ---------------------------------");
                        }
                    }, null);
                } catch (Exception localException) {
                    localException.printStackTrace();
                }
            }
        }, 15000);
    }

    private void clickViewByXy(final int x, final int y) {
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.w(TAG, "------------------------- clickViewByXy x = " + x + " y = " + y);
                    GestureDescription.Builder localBuilder = new GestureDescription.Builder();
                    Path path = new Path();
                    path.moveTo(x + 10, y);//140 1448  536 1231 525 1250
                    path.lineTo(x + 10, y + 2);//140 1449
                    localBuilder.addStroke(new GestureDescription.StrokeDescription(path, 150L, 100L));
                    dispatchGesture(localBuilder.build(), new GestureResultCallback() {
                        public void onCancelled(GestureDescription paramAnonymousGestureDescription) {
                            super.onCancelled(paramAnonymousGestureDescription);
                            Log.e(TAG, "------------------------- clickView ByXy失败 ---------------------------------");
                        }

                        public void onCompleted(GestureDescription paramAnonymousGestureDescription) {
                            super.onCompleted(paramAnonymousGestureDescription);
//                            isDakFinish = true;
                            index = STEP_DO_KAOQIN;
//                            lightHandler.removeMessages(SEND_MESG);
//                            lightHandler.sendEmptyMessageDelayed(SEND_MESG, 5000);
                            Log.w(TAG, "------------------------- clickViewByXy 完成 ---------------------------------");


                        }
                    }, null);
                } catch (Exception localException) {
                    localException.printStackTrace();
                }
            }
        }, 10);
    }

    //递归获取所有节点
    private List<AccessibilityNodeInfo> getAllNode(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        if (node != null && node.getChildCount() != 0) {
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo info = node.getChild(i);
                if (node != null) {
                    list.add(info);
                    node = info;
                }
            }

        } else {
            return list;
        }
        return getAllNode(node, list);
    }

    //通过文字点击
    private boolean click(String viewText) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
//        List<AccessibilityWindowInfo> windowInfo=getWindows();
        try {
            //点击前滞留1s
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (nodeInfo == null) {
            Log.w(TAG, "点击失败，rootWindow为空");
            return false;
        }
        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText(viewText);

        if (list.isEmpty()) {
            //没有该文字的控件
            Log.w(TAG, "点击失败，" + viewText + "控件列表为空");
            return false;
        } else {
            for (AccessibilityNodeInfo info : list) {
                if (viewText.equals(info.getText().toString())) {
                    return onclick(info);  //遍历点击
                }
            }
            return false;
        }

    }

    private boolean comClickByID(String str) {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        List<AccessibilityNodeInfo> list1 = nodeInfo.findAccessibilityNodeInfosByViewId(str);
        if (list1 == null || list1.size() == 0) {
            Log.e("DingService", "click(DingService.java:763)" + "点击失败！" + str);
            return false;
        } else {
            Log.w("DingService", "click(DingService.java:766)" + "点击成功！" + str);
            list1.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            return true;
        }
    }

    private void clickGesture() {
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //模拟上滑手势
                try {
                    GestureDescription.Builder localBuilder = new GestureDescription.Builder();
                    Path path = new Path();
                    path.moveTo(140, 1448);//140 1448  536 1231
                    path.lineTo(140, 1449);//140 1449
                    localBuilder.addStroke(new GestureDescription.StrokeDescription(path, 150L, 100L));
                    dispatchGesture(localBuilder.build(), new GestureResultCallback() {
                        public void onCancelled(GestureDescription paramAnonymousGestureDescription) {
                            super.onCancelled(paramAnonymousGestureDescription);
                            Log.e(TAG, "------------------------- 点击考勤失败 ---------------------------------");
                        }

                        public void onCompleted(GestureDescription paramAnonymousGestureDescription) {
                            super.onCompleted(paramAnonymousGestureDescription);
                            isClickKaoqin = true;
                            Log.w(TAG, "------------------------- 点击考勤完成 ---------------------------------");
                        }
                    }, null);
                } catch (Exception localException) {
                    localException.printStackTrace();
                }
            }
        }, 2000);
    }

    public static void execShellCmd(String cmd) {
        try {
            // 申请获取root权限，这一步很重要，不然会没有作用
            Process process = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(
                    outputStream);
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();
        } catch (Throwable t) {
            Log.e("DingService",
                    "execShellCmd(DingService.java:735)" + "执行失败---》" + cmd);
            t.printStackTrace();
        }
    }

    private boolean onclick(AccessibilityNodeInfo view) {
        if (view == null) {
            Log.w(TAG, "node 为空无法点击");
            return false;
        }
        if (view.isClickable()) {
            view.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            Log.w(TAG, "view name" + view.getClassName() + "+点击成功");
            Log.w(TAG, "view text" + view.getText());
            return true;
        } else {

            AccessibilityNodeInfo parent = view.getParent();
            if (parent == null) {
                return false;
            }
            return onclick(parent);
        }
    }

    //点击返回按钮事件
    private void keepScreem() {
        click("确定");
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                click("确定");
            }
        }, 1000);
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.e("DingService", "run(DingService.java:928)" + "准备截屏");
                //这里启动新的透明的activity后 上个页面的dialog 键盘可能会因为页面pause而隐藏.
                try {
                    Intent i = new Intent("androidyuan.shotter");
                    // 这个不是必需的
                    //i.addCategory(Intent.CATEGORY_DEFAULT);
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 3000);

        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.e("DingService", "run(DingService.java:1026)" + "准备发送截图邮件");
                Timer timer = new Timer();
                TimerTask mSendTask = new TimerTask() {
                    @Override
                    public void run() {
                        sendMailMsgwithImg("123", "/storage/emulated/0/111cardImg.png");
                        Log.e("DingService", "run(DingService.java:1026)" + "准备发送截图邮件22");

                        performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);

                    }
                };
                timer.schedule(mSendTask, 4 * 1000);
            }
        }, 1000);
    }

    @Override
    public void onInterrupt() {

    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.i(TAG, "service connected!");
        Toast.makeText(getApplicationContext(), "连接成功！", Toast.LENGTH_LONG).show();
        instance = this;
    }

    public void wakeUpAndUnlock(Context context) {
        //获取电源管理器对象
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
        //点亮屏幕
        wl.acquire();
        //释放
        km.isKeyguardLocked();
        wl.release();
        if (!pm.isScreenOn()) {
            if (lightHandler != null && mCountBtnCLick == 0) {
                lightHandler.sendEmptyMessage(LIGHT_START);
            } else {
                Log.e(TAG, "lightHandler can not be null or is click working  now");
            }
        }
        if (km.isKeyguardLocked()) {
            kl.disableKeyguard();
            km.exitKeyguardSecurely(new KeyguardManager.OnKeyguardExitResult() {
                @Override
                public void onKeyguardExitResult(boolean success) {
                    if (success) {
                        Log.i(TAG, " keyGarud is Unlocked -_-");
                    } else {
                        Log.i(TAG, " keyGarud is locked ,unlock again");
                        if (kl != null) {
                            kl.reenableKeyguard();
                        }
                        kl.disableKeyguard();
                        km.exitKeyguardSecurely(this);
                    }
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void LoginSuccess(String str) {
        //开始打卡流程
        toast("开始打卡" + str);
        prepareForKaoQin();
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "----######---server is onDestroy  ----######---");
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        mContext = null;
        lightHandler = null;
    }

    private void createNotifition() {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentText("钉钉打卡服务监控");
        builder.setContentTitle("钉钉打卡");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setTicker("钉钉打卡服务监控");
        builder.setAutoCancel(true);
        builder.setWhen(System.currentTimeMillis());
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 10, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(pendingIntent);
        Notification notification = builder.build();
        startForeground(NOTIFICATION_ID, notification);
    }

    public static int NOTIFICATION_ID = 10000;

    public String getLastImgPath() {
        String fullPicPath = "none";
        if (mContext != null) {
            File piDir = new File(getSDPath() + "/DCIM/Screenshots/");
            if (piDir != null && piDir.isDirectory()) {
                File[] pics = piDir.listFiles();
                if (pics != null && pics.length > 0) {
                    for (int i = 0; i < pics.length; i++) {
                        if (i == 0) {
                            fullPicPath = pics[i].getAbsolutePath();
                        } else {
                            if (pics[i].lastModified() > pics[i - 1].lastModified()) {
                                fullPicPath = pics[i].getAbsolutePath();
                            }
                        }
                    }
                }
            }
        }
        return fullPicPath;
    }

    public String getSDPath() {
        File sdDir = new File("/mnt/sdcard");
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    public void sendMailMsgwithImg(String msg1, String imgurl) {
        try {
            String sendMsg = "[" + DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString() + "]" + msg1;
            Properties props = new Properties();
            // 开启debug调试
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            props.setProperty("mail.debug", "false");
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.host", "smtp.qq.com");

            props.setProperty("mail.smtp.auth", "true");

            // 设置环境信息
            Session session = Session.getInstance(props);

            // 创建邮件对象
            javax.mail.Message msg = new MimeMessage(session);
            msg.setSubject("打卡记录");
            /***********************/
            MimeBodyPart text = new MimeBodyPart();
            // setContent(“邮件的正文内容”,”设置邮件内容的编码方式”)
            text.setContent(msg1 + "<img src='cid:a'>", "text/html;charset=utf-8");
            MimeBodyPart img = new MimeBodyPart();
            /*
             * JavaMail API不限制信息只为文本,任何形式的信息都可能作茧自缚MimeMessage的一部分.
             * 除了文本信息,作为文件附件包含在电子邮件信息的一部分是很普遍的.
             * JavaMail API通过使用DataHandler对象,提供一个允许我们包含非文本BodyPart对象的简便方法.
             */
            DataHandler dh = new DataHandler(new FileDataSource(imgurl));
            img.setDataHandler(dh);
            //创建图片的一个表示用于显示在邮件中显示
            img.setContentID("a");
            //关系   正文和图片的
            MimeMultipart mm = new MimeMultipart();
            mm.addBodyPart(text);
            mm.addBodyPart(img);
            mm.setSubType("related");//设置正文与图片之间的关系
            //图班与正文的 body
            MimeBodyPart all = new MimeBodyPart();
            all.setContent(mm);
            //附件与正文（text 和 img）的关系
            MimeMultipart mm2 = new MimeMultipart();
            mm2.addBodyPart(all);
            mm2.setSubType("mixed");//设置正文与附件之间的关系
            msg.setContent(mm2);
            msg.saveChanges(); //保存修改
            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
            /***********************/
//            // 设置发件人
//            msg.setFrom(new InternetAddress(CONFIG_QQ_NUM1 + "@qq.com"));
//            //发送邮件
//            Transport transport = session.getTransport();
//            transport.connect("smtp.qq.com", CONFIG_QQ_NUM1 + "@qq.com", CONFIG_QQ_MAIL);
//
//            transport.sendMessage(msg, new Address[]{new InternetAddress(CONFIG_QQ_NUM1 + "@qq.com")});
//            transport.close();
//
//            System.out.println("成功");

            // 设置发件人
            msg.setFrom(new InternetAddress("978599733@qq.com"));
            //发送邮件
            Transport transport = session.getTransport();
            transport.connect("smtp.qq.com", "978599733@qq.com", "gneoskqqchqgbbch");

            transport.sendMessage(msg, new Address[]{new InternetAddress("978599733@qq.com")});
            transport.close();
        } catch (Exception e) {
            Log.e("DingService", "sendMailMsgwithImg(DingService.java:1069)发送失败" + e.getMessage());
            e.printStackTrace();
        }
    }

    public void sendMailMsg(String msg1) {
        Log.e(TAG, "sendMailMsg(DingService.java:884)" + "发送邮件--->" + msg1 + "");
        try {
            String sendMsg = "[" + DateFormat.format("yyyy-MM-dd hh:mm:ss", System.currentTimeMillis()).toString() + "]" + msg1;
            Properties props = new Properties();
            // 开启debug调试
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            props.setProperty("mail.debug", "false");
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.host", "smtp.qq.com");

            props.setProperty("mail.smtp.auth", "true");

            // 设置环境信息
            Session session = Session.getInstance(props);

            // 创建邮件对象
            javax.mail.Message msg = new MimeMessage(session);
            msg.setSubject("打卡记录");
            // 设置邮件内容
            msg.setText(sendMsg);
            // 设置发件人
            msg.setFrom(new InternetAddress("978599733@qq.com"));
            //发送邮件
            Transport transport = session.getTransport();
            transport.connect("smtp.qq.com", "978599733@qq.com", "gneoskqqchqgbbch");

            transport.sendMessage(msg, new Address[]{new InternetAddress("978599733@qq.com")});
            transport.close();

            System.out.println("成功");
        } catch (MessagingException mex) {
            Log.e("DingService", "sendMailMsg(DingService.java:920)" + "发送邮件失败--->" + mex.getMessage());
        } catch (Exception e) {
            Log.e("DingService", "sendMailMsg(DingService.java:920)" + "发送邮件失败--->" + e.getMessage());
            e.printStackTrace();
        }
    }

    private boolean flag = false;

    private boolean clickMenue() {
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME);
            }
        }, 500);
       /* new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS);
            }
        }, 1000);
        //550 1795 com.vivo.upslide:id/clear_all
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    GestureDescription.Builder localBuilder = new GestureDescription.Builder();
                    Path path = new Path();
                    path.moveTo(532, 1765);
                    path.lineTo(532, 1765);
                    localBuilder.addStroke(new GestureDescription.StrokeDescription(path, 100L, 50L));
                    dispatchGesture(localBuilder.build(), new GestureResultCallback() {
                        public void onCancelled(GestureDescription paramAnonymousGestureDescription) {
                            super.onCancelled(paramAnonymousGestureDescription);
                            flag = false;
                            Log.e(TAG, "------------------------- 点击Clear失败---------------------------------");
                        }

                        public void onCompleted(GestureDescription paramAnonymousGestureDescription) {
                            super.onCompleted(paramAnonymousGestureDescription);
                            flag = true;
                            Log.w(TAG, "------------------------- 点击Clear完成---------------------------------");
                        }
                    }, null);
                } catch (Exception localException) {
                    localException.printStackTrace();
                }
            }
        }, 2000);*/
        return flag;
    }

    public void toast(String str) {
        Log.e("DingService", "toast: " + str);
        Toast.makeText(DingService.this, str, Toast.LENGTH_SHORT).show();
    }
}


/**
 * com.seeyon.cmp:id/main_tab_img_icon
 * <p>
 * content-desc考勤打卡
 * <p>
 * content-desc打卡
 */

//getViewAndClick(getRootInActiveWindow(), "下班打卡");
//android:id/button1 确定
//com.android.settings

//com.android.settings:id/right_button
//强行停止
